import { Injectable } from '@nestjs/common';
import { OrgPageQuery } from './dto/org.page.query';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { SysOrg } from './entities/org.entity';
import { PageResult } from '../../common/result/PageResult';
import { Result } from '../../common/result/Result';
import { OrgForm } from './dto/org.form';
import { ResultCode } from '../../common/result/ResultCode';
import { JwtUtils } from '../01_auth/jwt.utils';
// import { SysRoleMenu } from './entities/role.menu.entity';
import { JwtPayload } from '../01_auth/jwt.payload';

@Injectable()
export class OrgService{
  constructor(
    @InjectRepository(SysOrg)
    private orgRepository: Repository<SysOrg>, // mysql数据库连接工具

    // @InjectRepository(SysRoleMenu)
    // private roleMenuRepository: Repository<SysRoleMenu>,
    private jwt: JwtUtils, // 验签管理器（token）
  ) {}
  async getPage(query: OrgPageQuery): Promise<PageResult<SysOrg>> {
    const queryBuilder = this.orgRepository
      .createQueryBuilder('su')
      .orderBy(query.sort,query.order)
      .skip((query.pageNum - 1) * query.pageSize)
      .take(query.pageSize);
    if(query.code){
      queryBuilder.andWhere(
        'su.code LIKE :code)',
        { code: `%${query.code}%`},
      );
    }
    if(query.name){
      queryBuilder.andWhere(
        'su.name LIKE :name)',
        { name: `%${query.name}%`},
      );
    }   
    const result = await queryBuilder.getManyAndCount();
    return PageResult.success(result[0], result[1]);
  }

  async saveOrg(form: OrgForm, payload: JwtPayload): Promise<Result<any>> {
    // 1. 检验该组织编码是否存在
    const flag = await this.orgRepository.exists({
      where: { name: form.name },
    });
    console.log(flag)
    // if (flag) {
    //   return Result.failed(ResultCode.ROLE_HAS_EXISTS);
    // }
    // 2. 插入角色信息
    // const role = new SysRole({
    //   createUser: payload.nickname,
    //   createBy: payload.userId,
    //   updateUser: payload.nickname,
    //   updateBy: payload.userId,
    // });
    // 3. 插入
    // role.code = form.code;
    // role.status = form.status;
    // role.sort = form.sort;
    // role.dataScope = form.dataScope;
    // role.name = form.name;
    // await this.roleRepository.save(role);
    return Result.success();
  }
}